/*
* 生产工序列表模块
*/
const express = require('express');
const router = express.Router();
// 引入数据库
const db = require("../../../config/db");
// 引入时间包
const moment = require("moment");
// 引入方法库
const { toCamelCase, toUnderlineCase, verifyToken} = require("../../../config/utils");
// 引入日志
const log = require("../../log");

// 查询所有有效生产工序
router.get("/listAll", (req, res) => {
    console.log("===========查询所有有效生产工序接口============");

    let sql = `select * from pro_process where enable_flag = 'Y'`;
    // 查询数据库
    db.query("查询所有有效生产工序", sql, (err, result) => {
        if (err) {
            res.send({code: 500, msg: "查询所有有效生产工序失败"})   
            return
        }
        if (result.length > 0) {
            // 变量Json数组key转成下划线第一个大写
            result = result.map(item => {
               return toCamelCase(item)
           })
       }
       res.send({code: 200, msg: "查询所有有效生产工序成功", data: result})
    })
})

// 查询所有生产工序
router.get("/list", (req, res) => {
    console.log("===========查询所有生产工序接口============");
    // 获取参数
    let {pageNum, pageSize, processCode, processName, enableFlag} = req.query;
    // 拼接sql语句
    let sql = "select * from pro_process";
    let sql_where = ` where 1=1`;
    if(processCode){
        sql_where += ` and process_code like '%${processCode}%'`;
    }
    if(processName){
        sql_where += ` and process_name like '%${processName}%'`;
    }
    if(enableFlag){
        sql_where += ` and enable_flag = '${enableFlag}'`;
    }
    if(processCode || processName  || enableFlag){
        sql += sql_where;
    }
    
    // 分页
    sql += ` limit ${(pageNum-1)*pageSize}, ${pageSize}`;
    // 查询数据库
    db.query("查询生产工序列表", sql, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询生产工序列表失败", data: err});
            return;
        }
        // 查询总数
        db.query("查询生产工序总数", `select count(*) as count from pro_process ${sql_where}`, (err, count)=>{
            if(err){
                res.send({code: 500, msg: "查询生产工序总数失败", data: err});
                return;
            }
            if(result.length > 0){
                 // 变量Json数组key转成下划线第一个大写
                 result = result.map(item => {
                    return toCamelCase(item)
                })
                res.send({code: 200, msg: "查询生产工序列表成功", rows: result, total: count[0].count});
            }else{
                res.send({code: 200, msg: "查询生产工序列表成功", data: [], total: 0});
            }
        })
    })
})

// 添加生产工序
router.post("/", async (req, res) => {
    console.log("===========添加生产工序接口============");
    // 获取参数
    let { processCode, processName, attention, enableFlag, remark } = req.body;
     // 获取创建人
     let {username} = verifyToken(req.headers.authorization);
     // 获取创建时间
     let createTime = moment().format("YYYY-MM-DD HH:mm:ss");
     // 判断生产工序编码和生产工序名称是否重复
     db.query("查询生产工序编码是否重复", `select * from pro_process where process_code='${processCode}' or process_name = '${processName}'`, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询生产工序编码是否重复失败", data: err});
            return;
        }
        if(result.length > 0){
            res.send({code: 500, msg: "生产工序编码或生产工序名称已存在", data: []});
            return;
        }
        // 插入数据库
        let sql = `insert into pro_process (process_code, process_name, attention, enable_flag, remark, create_by, create_time) 
        values('${processCode}', '${processName}', ${attention ? "'"+attention+"'" : null}, '${enableFlag}', ${remark ? "'"+remark+"'" : null}, '${username}', '${createTime}')`;
        db.query("添加生产工序", sql, (err, result)=>{
            if(err){
                res.send({code: 500, msg: "添加生产工序失败", data: err});
                return;
            }
            if(result.affectedRows > 0){
                res.send({code: 200, msg: "添加生产工序成功", data: []});
            }else{
                res.send({code: 500, msg: "添加生产工序失败", data: []});
            }
        })
     })
})

// 查询单个生产工序
router.get(/^\/(\d+)$/, (req, res) => {
    console.log("===========查询单个生产工序接口，正则匹配============");
    // 获取参数
    let url_arr = req.url.split("/");
    const id = url_arr[url_arr.length - 1];
   
    db.query("查询单个生产工序", `select * from pro_process where process_id = ${id}`, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询单个生产工序失败", data: err});
            return;
        }
        if(result.length > 0){
            // 变量Json数组key转成下划线第一个大写
            result = result.map(item => {
                return toCamelCase(item)
            })
            res.send({code: 200, msg: "查询单个生产工序成功", data: result[0]});
        }else{
            res.send({code: 500, msg: "查询单个生产工序失败"});
        }
    })
})

// 修改生产工序
router.put("/", (req, res)=>{
    console.log("===========修改生产工序接口============");
    // 获取参数
    let { processId, processCode, processName, attention, enableFlag, remark } = req.body;
    // 获取修改人
    let {username} = verifyToken(req.headers.authorization);
    // 获取修改时间
    let updateTime = moment().format("YYYY-MM-DD HH:mm:ss");
    // 查询生产工序名称是否重复
    db.query("查询生产工序名称是否重复", `select * from pro_process where process_id != ${processId} and (process_code='${processCode}' or process_name = '${processName}')`, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询生产工序名称是否重复失败", data: err});
            return;
        }
        if(result.length > 0){
            res.send({code: 500, msg: "生产工序编码或生产工序名称已存在", data: []});
            return;
        }
        // 修改生产工序sql
        let sql = `update pro_process set process_code='${processCode}', process_name='${processName}',
        attention=${attention ? "'"+attention+"'" : null}, enable_flag='${enableFlag}', remark=${remark ? "'"+remark+"'" : null}, update_by='${username}', 
        update_time='${updateTime}' where process_id = ${processId}`;
        db.query("修改生产工序", sql, (err, result)=>{
            if(err){
                res.send({code: 500, msg: "修改生产工序失败", data: err});
                return;
            }
            if(result.affectedRows > 0){
                res.send({code: 200, msg: "修改生产工序成功", data: []});
            }else{
                res.send({code: 500, msg: "修改生产工序失败", data: []});
            }
        })
    })
})

// 删除生产工序
router.delete("/:id", (req, res) => {
    console.log("===========删除生产工序接口============");
    // 获取参数
    let {id} = req.params;
     // 拼接sql,删除多条数据
     let sql = `delete from pro_process where process_id in(${id})`;
    // 查询数据库
    db.query("删除生产工序", sql, (err, result) => {
        if (err) {
            res.send({code: 500, msg: "删除生产工序失败", data: err});
            return
        }
        if(result.affectedRows > 0){
            res.send({code: 200, msg: "删除生产工序成功"})
        }else{
            res.send({code: 500, msg: "删除生产工序失败"})
        }
    })
})


module.exports = router;